/*
 * @Author: your name
 * @Date: 2022-02-12 21:40:36
 * @LastEditTime: 2022-02-15 18:11:30
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vue3.2\src\api\request.js
 */
import axios from 'axios'
import {
  ElMessage
} from 'element-plus'
import {
  diffTokenTime
} from '../utils/auth'
import store from '../store'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})
service.interceptors.request.use(config => {
  if (localStorage.getItem('token')) {
    if (diffTokenTime()) {
      store.dispatch('app/logout')
      return Promise.reject(new Error('token 失效了'))
    }
  }
  config.headers.Authorization = localStorage.getItem('token')
  return config
}, error => {
  return Promise.reject(new Error(error))
})
service.interceptors.response.use(
  (response) => {
    const {
      data,
      meta
    } = response.data
    if (meta.status === 200 || meta.status === 201) {
      return data
    } else {
      ElMessage.error(meta.msg)
      return Promise.reject(new Error(meta.msg))
    }
  }, error => {
    error.response && ElMessage.error(error.ElMessage.data)
    return Promise.reject(new Error(error.ElMessage.data))
  })

export default service
